package com.chenliwu.demo.java8.stream;

import java.util.Arrays;
import java.util.IntSummaryStatistics;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;

/**
 * FilterDemo
 *
 * @author chenliwu
 * @since 2022-06-13
 */
public class StreamDemo {

    public static void main(String[] args) {
        testFiler();

        testCount();

        testDistinct();

        testSorted();

        testCollector();

        testLimit();

        testSkip();
    }

    private static void testFiler() {
        List<String> stringList = Arrays.asList("aaa", "bbb", "", "", "ccc", "ddd", "eee", "aaa");
        // 获取stringList中非空字符串的集合
        List<String> collect = stringList.stream().filter(str -> !str.isEmpty())
                .collect(Collectors.toList());
        System.out.println("非空字符串集合：" + collect);
    }

    private static void testCount() {
        List<String> stringList = Arrays.asList("aaa", "bbb", "", "", "ccc", "ddd", "eee", "aaa");
        long emptyStrNum = stringList.stream().filter(String::isEmpty).count();
        System.out.println("空字符串数量 = " + emptyStrNum);
    }

    private static void testDistinct() {
        List<String> stringList = Arrays.asList("aaa", "bbb", "ccc", "aaa", "bbb", "ccc");

        List<String> collect = stringList.stream().filter(str -> !str.isEmpty()).distinct()
                .collect(Collectors.toList());
        System.out.println("去重后字符串集合：" + collect);
    }

    private static void testSorted() {
        List<Integer> integerList = Arrays.asList(3, 2, 1, 4, 5, 6);
        System.out.println("排序后的集合：" + integerList.stream().sorted().collect(Collectors.toList()));
    }

    private static void testCollector() {
        // 定义一个int类型的集合
        List<Integer> numbers = Arrays.asList(3, 2, 1, 4, 5, 6);
        // 通过mapToInt转化
        IntSummaryStatistics intStatus = numbers.stream().mapToInt((integer) -> integer).summaryStatistics();

        System.out.println("列表中元素数量：" + intStatus.getCount());
        System.out.println("列表中最小数 : " + intStatus.getMin());
        System.out.println("列表中最大数 : " + intStatus.getMax());
        System.out.println("所有数之和 : " + intStatus.getSum());
        System.out.println("平均值 : " + intStatus.getAverage());
    }

    private static void testLimit() {
        Random random = new Random();
        // 通过 limit 输出3个随机数
        // 三个参数：random.ints(生成数量，最小值，最大值）
        // 生成10个1-100之间的随机数，再通过limit取出5个输出
        random.ints(10, 1, 100).limit(5).forEach(r -> {
            System.out.print(r + " ");
        });
        System.out.println();
    }

    private static void testSkip() {
        List<Integer> numbers = Arrays.asList(0, 9, 6, 5, 6, 3, 2, 1, 12, 5, 8, 3, 9, 3);
        // 过滤得到集合中>1的元素，然后去重，跳过前2个，然后取出5个
        List<Integer> collect = numbers.stream().filter(i -> i > 1)
                .distinct()
                .skip(2)
                .limit(5).collect(Collectors.toList());
        System.out.println(collect);
    }

}
